<?php

// +----------------------------------------------------------------------
// | 分销管家
// +----------------------------------------------------------------------
// | Copyright (c) 2015 http://www.kmeen.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: xzake <http://www.kmeen.com>
// +----------------------------------------------------------------------

namespace Manage\Controller;

/**
 * 导出控制器
 * @author xzake
 */
class ExportController extends AdminController {

    public function index() {

        $this->meta_title = '导出信息';
        $this->display();
    }

    public function member() {


        dump(I('param.'));
        $filename = "全部会员信息";

        $where = '';
        $date = I('post.member_date');

        if (IS_POST && !empty($date)) {

            $dates = explode(" - ", $date);
            dump($dates);
            $filename = $dates[0] . "至" . $dates[1] . "会员信息";
            $start = strtotime($dates[0]);
            $end = strtotime($dates[1]) + 86400;
//            dump($dates);
            $where.=" and m1.create_time >= $start and m1.create_time < $end";
            // exit;
        }

        $sql = "SELECT m1.id,"
                . " m1.nickname, "
                . " m2.nickname AS pname, "
                . " m1.pid, "
                . " m1.balance, m1.power,"
                . " m1.login_time, m1.login_count,"
                . " m1.create_time,"
                . " m1.`status`,"
                . " m1.`name`, m1.phone, "
                . " m1.wechat, m1.email  "
                . "FROM kmeen_member AS m1 "
                . "LEFT JOIN kmeen_member AS m2 "
                . "ON m1.pid = m2.id" . " where 1=1" . $where;

    
        $members = M('Member')->query($sql);

        if (empty($members)) {
            $this->error("找不到指定条件的会员信息");
        }
//        echo M()->getLastSql();
//        dump($members);
        $data = array();

        foreach ($members as $member) {

            $tempArr = array();

            $member['login_time'] = date("Y-m-d h:i:s", $member['login_time']);
//            $member['nickname'] = $member['nickname'] . " ";
//            $member['pname'] = $member['pname'] . " ";
            $member['create_time'] = date("Y-m-d h:i:s", $member['create_time']);

            if ($member['power'] >= 3) {
                $member['power'] = "分销商";
            } else {
                $member['power'] = "普通会员";
            }

            if ($member['status'] == 1) {
                $member['status'] = "正常";
            } else {
                $member['status'] = "冻结";
            }
            if (empty($member['pname'])) {
                $member['pname'] = "官网";
            }


            $where = array();
            $where['user_id'] = array('eq', $member['id']);

            $allcount = M('MemberCommission')->where($where)->sum('commission');
            $where['status'] = array('eq', 1);
            $acount = M('MemberCommission')->where($where)->sum('commission');
//            echo M()->getLastSql();
//            dump($count);
//            exit;

            $tempArr[0] = $member['id'];
            $tempArr[1] = $member['nickname'];
            $tempArr[2] = empty($allcount) ? 0 : $allcount;
            $tempArr[3] = empty($acount) ? 0 : $acount;

            $tempArr[5] = $member['pname'];
            $tempArr[6] = $member['pid'];
            $tempArr[7] = $member['balance'];
            $tempArr[8] = $member['power'];
            $tempArr[9] = $member['login_time'];
            $tempArr[10] = $member['login_count'];
            $tempArr[11] = $member['create_time'];
            $tempArr[12] = $member['status'];
            $tempArr[13] = $member['name'];
            $tempArr[14] = $member['phone'];
            $tempArr[15] = $member['wechat'];
            $tempArr[16] = $member['email'];
            $data[] = $tempArr;
        }

        $headArr = array("用户ID", "昵称", "总佣金", "已发放佣金", "推荐者", "推荐者ID", "余额", "分销商",
            "最近登录时间", "登录次数", "注册时间", "状态", "姓名", "手机", "微信号", "邮箱");
        $this->getExcel($filename, $headArr, $data);
    }

    public function order() {
        $filename = "全部订单信息";

        $where = '';
        $date = I('post.member_date');

        if (IS_POST && !empty($date)) {

            $dates = explode(" - ", $date);
            $filename = $dates[0] . "至" . $dates[1] . "订单信息";
            $start = strtotime($dates[0]);
            $end = strtotime($dates[1]) + 86400;
//            dump($dates);
            $where.=" and ko.create_time >= $start and ko.create_time < $end";
            // exit;
        }

        $sql = "SELECT ko.id, ko.user_id, ko.`order_order_no`,"
                . " ko.total, ko.ids, ko.pnum, ko.`name`,"
                . " ko.phone, ko.province, ko.city,"
                . " ko.area, ko.street, ko.address,"
                . " ko.postcode, ko.remark, ko.express_name,"
                . " ko.express_order_no, ko.pay_order_no, ko.pay_status,"
                . " ko.send_status, ko.confirm_time, ko.commission_status,"
                . " ko.create_time, ko.sort,"
                . " ko.`status`, km.nickname FROM kmeen_order AS ko"
                . " LEFT JOIN kmeen_member AS km"
                . " ON ko.user_id = km.id" . " where 1=1" . $where;

//        echo $sql;

        $orders = M('Order')->query($sql);

        if (empty($orders)) {
            $this->error("找不到指定条件的订单信息");
        }
//        echo M()->getLastSql();
//        dump($members);
        $data = array();

        $rule = explode("|", C('FX_RULE'));
//        dump($rule);
//        dump(array_sum($rule) / 100);
        $rate = array_sum($rule) / 100;
//        EXIT;

        foreach ($orders as $item) {

            $tempArr = array();

            $item['confirm_time'] = date("Y-m-d h:i:s", $item['confirm_time']);
            $item['create_time'] = date("Y-m-d h:i:s", $item['create_time']);


            $where = array();
            $where['order_order_no'] = array('eq', $item['order_no']);

//            $allcount = M('OrderGoods')->where($where)->sum('commission');
//            $where['status'] = array('eq', 1);
            $acount = M('MemberCommission')->where($where)->sum('commission');
//            echo M()->getLastSql();
//            dump($allcount);
//            exit;

            $tempArr[0] = $item['id'];
            $tempArr[1] = $item['order_no'] . " ";
            $tempArr[2] = $item['total'];
            $tempArr[3] = $item['total'] < 210 ? C('GOODS_TRANSPORT') : 0;
            $tempArr[4] = $item['total'] * $rate;
            $tempArr[5] = empty($acount) ? 0 : $acount;

            //根据订单id查询订单产品信息
            $orderGoods = M("OrderGoods")->where($where)->select();
            $ptitle = "";
            foreach ($orderGoods as $g) {
                $ptitle.=$g['title'] . "({$g['pnum']}) | ";
            }
            $tempArr[6] = $ptitle;
            $tempArr[7] = $item['pnum'];

            $tempArr[8] = $item['user_id'];
            $tempArr[9] = $item['nickname'];
            $tempArr[10] = $item['name'];
            $tempArr[11] = $item['phone'];
            $tempArr[12] = $item['province'] . $item['city'] . $item['area'] . $item['address'] . $item['postcode'];
            $tempArr[13] = $item['create_time'];

            $statusStr = get_order_status($item['pay_status'], $item['send_status'], $item['status']);
            if ($data['commission_status'] == 0) {
                $statusStr .= " | 未放佣";
            } else {
                $statusStr .= " | 已放佣";
            }
            $tempArr[14] = $statusStr;


            $data[] = $tempArr;
        }
       dump($data);exit;

        $headArr = array("订单ID", "订单号", "订单金额", "运费", "总佣金", "实际发放", "产品信息", "产品数量", "会员ID", "会员昵称", "收货人", "收货人手机", "收货地址",
            "下单时间", "状态");
        $this->getExcel($filename, $headArr, $data);
    }

    /**
     * 红包提现细心
     * @param type $fileName
     * @param type $headArr
     * @param type $data
     */
    public function redinfomation() {
        $filename = "全部红包提现信息";

        $where = '';
        $date = I('post.member_date');

        if (IS_POST && !empty($date)) {

            $dates = explode(" - ", $date);
            $filename = $dates[0] . "至" . $dates[1] . "红包提现信息";
            $start = strtotime($dates[0]);
            $end = strtotime($dates[1]) + 86400;
//            dump($dates);
            $where.=" create_time >= $start and create_time < $end";
            // exit;
        }
//         $sql = "SELECT id,"
//                . " user_id, "
//                . " name, "
//                . " billorder_no,"
//                . " data,"
//                . " create_time "
//                . "FROM kmeen_member_cash_log " ."where 1=1 ".$where;
//        // echo $sql;
//        //dump($where);
//        $MemerCashRed = M('MemerCashRed')->query($sql);
//        //echo M($MemerCashRed)->getlastSql();
        $MemerCashRed = M('MemerCashRed')->where($where)->select();

        if (empty($MemerCashRed)) {
            $this->error("找不到指定条件的红包提现信息");
        }
        $data = array();
        foreach ($MemerCashRed as $item) {

            $tempArr = array();

            $item['confirm_time'] = date("Y-m-d h:i:s", $item['confirm_time']);
            $item['create_time'] = date("Y-m-d h:i:s", $item['create_time']);

            $tempArr[0] = $item['id'];
            $tempArr[1] = $item['user_id'];
            $tempArr[2] = $item['name'];
            $tempArr[3] = $item['billorder_no'] . " ";
            if ($item['data'] == 'false') {
                $item['data'] = '失败';
            } else {
                $item['data'] = '成功';
            }
            $tempArr[4] = $item['data'];
            $tempArr[5] = $item['total'];
            $tempArr[6] = $item['create_time'];
            $data[] = $tempArr;
        }

        $headArr = array("ID", "会员ID", "会员昵称", "订单号", "提现状态", "提现金额", "提现时间");
        $this->getExcel($filename, $headArr, $data);
    }

    private function getExcel($fileName, $headArr, $data) {
        vendor('PHPExcel');

        //对数据进行检验
        if (empty($data) || !is_array($data)) {
            die("data must be a array");
        }
        //检查文件名
        if (empty($fileName)) {
            exit;
        }
        //创建PHPExcel对象，注意，不能少了\
        $objPHPExcel = new \PHPExcel();


        //设置基本信息
        $objPHPExcel->getProperties()->setCreator("kmeen")
                ->setLastModifiedBy("kmeen")
                ->setManager("kmeen")
                ->setTitle($fileName)
                ->setSubject($fileName)
                ->setDescription($fileName)
                ->setKeywords($fileName)
                ->setCompany("郑州仟米科技有限公司")
                ->setCategory($fileName);

        $objPHPExcel->setActiveSheetIndex(0);
        $objPHPExcel->getActiveSheet()->setTitle($fileName);

        $date = date("Y_m_d", time());
        $fileName .= "_{$date}.xlsx";

        //设置表头
        $key = ord("A");
        foreach ($headArr as $v) {
            $colum = chr($key);

            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $v);
            $objPHPExcel->getActiveSheet()->getColumnDimension($colum)->setAutoSize(true);
            $key += 1;
        }


        $column = 2;
        $objActSheet = $objPHPExcel->getActiveSheet();
        $objPHPExcel->getActiveSheet()->getStyle('B')->getNumberFormat()
                ->setFormatCode(\PHPExcel_Style_NumberFormat::FORMAT_TEXT);

        $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setAutoSize(true);

        foreach ($data as $key => $rows) { //行写入
            $span = ord("A");

            foreach ($rows as $keyName => $value) {// 列写入
                $j = chr($span);

                $objActSheet->setCellValue($j . $column, $value);

                $span++;

            }
            $column++;
        }

        header("Content-Type: application/force-download");
        header("Content-Type: application/octet-stream");
        header("Content-Type: application/download");
        header("Content-Type: application/vnd.ms-excel.numberformat:@");

        header("Content-Transfer-Encoding: binary");
        header("Content-Disposition: attachment;filename=\"$fileName\"");

        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Pragma: order_no-cache");

        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $objWriter->save('php://output'); //文件通过浏览器下载
        exit;
    }

    public function delivery_order($type = 0) {

        $filename = "需发货订单信息";
        $where = '';
        $date = I('post.member_date');

        if (IS_POST && !empty($date)) {

            $dates = explode(" - ", $date);
            $filename = $dates[0] . "至" . $dates[1] . "订单信息";
            $start = strtotime($dates[0]);
            $end = strtotime($dates[1]) + 86400;

            if ($type == 0) {
                $where.=" and ko.create_time >= $start and ko.create_time < $end and ko.status = 1 and ko.pay_status = 2 and ko.send_status = 0";
            } else {
                $where.=" and ko.create_time >= $start and ko.create_time < $end and ko.status = 1 and ko.pay_status = 2";
            }
        }

        $sql = "SELECT ko.id, ko.user_id, ko.`order_no`,"
                . " ko.total, ko.ids, ko.pnum, ko.`name`,"
                . " ko.phone, ko.province, ko.city,"
                . " ko.area, ko.street, ko.address,"
                . " ko.postcode, ko.remark,"
                . " ko.pay_no, ko.pay_status,"
                . " ko.send_status,"
                . " ko.create_time, ko.sort,"
                . " ko.`status`, km.nickname FROM kmeen_order AS ko"
                . " LEFT JOIN kmeen_member AS km"
                . " ON ko.user_id = km.id" . " where 1=1" . $where;

        $delivery_orders = M('Order')->query($sql);

        if (empty($delivery_orders)) {
            $this->error("没有指定条件的信息");
        }
        $data = array();


        foreach ($delivery_orders as $item) {

            $tempArr = array();

            $item['create_time'] = date("Y-m-d h:i:s", $item['create_time']);

            $where = array();
            $where['order_no'] = array('eq', $item['order_no']);

            $tempArr[0] = $item['id'];
            $tempArr[1] = $item['order_no'] . " ";
            $tempArr[2] = $item['total'];

            if ($item['pay_type'] == 0) {
                $tempArr[3] = '微信支付';
            } else {
                $tempArr[3] = '积分兑换';
            }

            //根据订单id查询订单产品信息
            $orderGoods = M("OrderGoods")->where($where)->select();
            $ptitle = "";
            foreach ($orderGoods as $g) {
                $ptitle.=$g['title'] . "({$g['count']}) | ";
            }
            $tempArr[4] = $ptitle;
            $tempArr[5] = $item['pnum'];
            $tempArr[6] = $item['user_id'];
            $tempArr[7] = $item['name'];
            $tempArr[8] = $item['phone'];
            $tempArr[9] = $item['province'] . $item['city'] . $item['area'] . $this->trimall($item['address']) . $item['postcode'];
            $tempArr[10] = $item['create_time'];

            $statusStr = get_order_status($item['pay_status'], $item['send_status'], $item['status']);
            $tempArr[11] = $statusStr;


            $data[] = $tempArr;
        }
      //  echo"<meta charset='utf-8'><pre>";print_r( $data );die();

        
        $headArr = array("订单ID", "订单号", "订单金额", "支付方式", "产品信息", "产品数量", "会员ID", "姓名", "电话", "地址",
            "下单时间", "状态");
        $this->getExcel($filename, $headArr, $data);
    }

    function trimall($str) {
        $qian = array(" ", "　", "\t", "\n", "\r");
        $hou = array("", "", "", "", "");
        return str_replace($qian, $hou, $str);
    }

    public function delCallback($model, $map) {
        
    }

}
